using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.Logic;
using NetProtocol.Client;
using NetProtocol.Enum;
using NetProtocol.POD;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class BattleModule : Singleton<BattleModule>, CNetBattle
    {
        private BattleModule() { }
        public static CNetBattle NetCore => Instance;

        void CNetBattle.SC_localNotifyCreateBattle(ISession session, LogicPlayerPOD playerPOD, CreateBattlePOD battlePOD)
        {
            CreateLocalBattle(playerPOD, battlePOD);
        }

        public void CreateLocalBattle(LogicPlayerPOD playerPod, CreateBattlePOD battlePod)
        {
            LogicHelper.OnPlayerEnterBattle = (pid, battleId) => NetCore.CS_localNotifyBattleStart(battleId);
            LogicHelper.OnPlayerLeaveBattle = (pid, battleId) => NetCore.CS_localNotifyBattleExit(battleId);
            LogicHelper.OnBattleEnd = OnBattleEnd;
            CBattleLogicModule.Instance.InitLocalBattle(battlePod, playerPod, null);
        }

        private void OnBattleEnd(BattleEndData battleEndData)
        {
            NotifyBattleEndPOD eventPOD = new NotifyBattleEndPOD()
            {
                pid = battleEndData.hostPlayerId,
                battleId = battleEndData.battleID,
                resultData = battleEndData.GeneratePOD() as BattleEndPOD,
                statisticsPOD = battleEndData.GenStatisticPOD(),
            };
            NetCore.CS_localNotifyBattleEnd(eventPOD);
        }

        void CNetBattle.SC_localNotifyShutdownBattle(ISession session, long battleId)
        {
            CBattleLogicModule.Instance.ShutdownLocalBattle();
        }

        ISession CNetBattle.GetSession()
        {
            return GameServerModule.Instance.CurrSession;
        }

        void CNetBattle.SC_notifyBattleSettlement(ISession session, BattleSettlementPOD battleSettlementPOD)
        {
            switch (battleSettlementPOD.battleType)
            {
                case BattleType.Test:
                    // 这里弹出了结算页面，离开逻辑交到UI处理
                    Debug.LogWarning($"SC_notifyBattleSettlement pod = {battleSettlementPOD}");
                    // CBattleLogicModule.NetCore.CS_RequestLeave();
                    var rData = BattleSettlementData.Parse(battleSettlementPOD);
                    ManagerCenter.UI.ShowWindow<UIBattleSettlement>(UD_BattleSettlement.Create(rData));
                    break;
                case BattleType.Level:
                    //关卡内部自己通知, 这里不实现
                    LogGame.LogError($"Not Support battleSettlement battleType = {battleSettlementPOD.battleType}");
                    break;
                default:
                    LogGame.LogError($"Not Support battleSettlement battleType = {battleSettlementPOD.battleType}");
                    break;
            }
        }
    }
}